const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');

const DATA_DIR = path.join(__dirname, 'data');
const TASKS_FILE = path.join(DATA_DIR, 'tasks.json');
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');

function ensureDataDir() {
  if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
  if (!fs.existsSync(CONFIG_FILE)) {
    fs.writeFileSync(CONFIG_FILE, JSON.stringify({
      theme: "light",
      reminderThresholdMinutes: 30,
      minimapLocked: true,
      storage: "file",
      dataFile: "tasks.json",
      configFile: "config.json",
      remoteLoad: "",
      remoteSave: ""
    }, null, 2), 'utf8');
  }
  if (!fs.existsSync(TASKS_FILE)) {
    fs.writeFileSync(TASKS_FILE, JSON.stringify({
      tasks: [],
      ideas: [],
      trash: [],
      config: null
    }, null, 2), 'utf8');
  }
}

function createWindow() {
  ensureDataDir();

  const win = new BrowserWindow({
    width: 1280,
    height: 860,
    minWidth: 1024,
    minHeight: 720,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  win.loadFile(path.join(__dirname, 'renderer', 'index.html'));
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

// 简单的文件读写 IPC（JSON 文本）
ipcMain.handle('file:read', (event, filename) => {
  const filePath = path.join(DATA_DIR, filename);
  if (!fs.existsSync(filePath)) return null;
  return fs.readFileSync(filePath, 'utf8');
});

ipcMain.handle('file:write', (event, filename, content) => {
  const filePath = path.join(DATA_DIR, filename);
  fs.writeFileSync(filePath, content, 'utf8');
  return true;
});
